﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace HardToolApp.Tool
{
    internal class BlockMap<TKey,TValue>
    {
        private Dictionary<TKey, TValue> map = new Dictionary<TKey, TValue>();
        private Dictionary<TKey, Semaphore> semMap = new Dictionary<TKey, Semaphore>();
        public TValue GetValue(TKey key,int timeout)
        {
            if(map.ContainsKey(key))
            {
                map.Remove(key);
            }
            if(semMap.ContainsKey(key))
            {
                semMap.Remove(key);
            }
            Semaphore semaphore = new Semaphore(0,1);
            semMap.Add(key, semaphore);
            if(semaphore.WaitOne(timeout) == false)
            {
                return default(TValue);
            }
            TValue value ;
            map.TryGetValue(key, out value);
            map.Remove(key);
            semMap.Remove(key);
            
            return value;
        }
        public void Add(TKey key,TValue value)
        { 
            try
            {
                map.Add(key, value);
            }
            finally
            {
                semMap[key].Release();
            }
            
        }
       
    }
}
